package com.yk.neon.lib.util.mybatis.repository;



import com.yk.neon.lib.util.mybatis.entity.Auditable;

import java.io.Serializable;
import java.util.Date;
import java.util.Objects;

public abstract class AbstractAuditableCrudRepository<T extends Auditable, ID extends Serializable, Example>
		extends AbstractCrudRepository<T, ID, Example> implements AuditableCrudRepository<T, ID> {

	@Override
	public <S extends T> S insert(S entity) {
		assembleCreateBy(entity);
		assembleOperation(entity);
		return super.insert(entity);
	}

	@Override
	public <S extends T> S update(S entity) {
		assembleOperation(entity);
		return super.update(entity);
	}

	@Override
	public <S extends T> S insertSelective(S entity) {
		assembleCreateBy(entity);
		assembleOperation(entity);
		getBaseMapper().insertSelective(entity);
		return entity;
	}

	@Override
	public <S extends T> S updateByPrimaryKeySelective(S entity) {
		assembleOperation(entity);
		getBaseMapper().updateByPrimaryKeySelective(entity);
		return entity;
	}

	public <S extends T> int updateByPrimaryKeySelectiveReturnUpdateCount(S entity) {
		assembleOperation(entity);
		return getBaseMapper().updateByPrimaryKeySelective(entity);
	}

	public <S extends T> int updateByExampleSelective(S entity, Example example) {
		assembleOperation(entity);
		return getBaseMapper().updateByExampleSelective(entity, example);
	}

	private <S extends T> void assembleCreateBy(S entity) {
		if (Objects.isNull(entity.getCreateDate())) {
			entity.setCreateDate(new Date());
		}
	}

	private <S extends T> void assembleOperation(S entity) {
		if (Objects.isNull(entity.getOperationDate())) {
			entity.setOperationDate(new Date());
		}
	}

}
